package cn.gzjp.modules.woms.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.Date;
import java.util.List;

import cn.gzjp.common.constant.Constants;
import cn.gzjp.modules.sys.entity.Office;
import cn.gzjp.modules.sys.entity.Role;
import cn.gzjp.modules.sys.entity.User;
import cn.gzjp.modules.sys.service.SystemService;
import cn.gzjp.modules.wx.service.QyWxService;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import cn.gzjp.common.utils.DateUtils;
import cn.gzjp.common.utils.MyBeanUtils;
import cn.gzjp.common.persistence.Page;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.common.utils.StringUtils;
import cn.gzjp.common.utils.excel.ExportExcel;
import cn.gzjp.common.utils.excel.ImportExcel;
import cn.gzjp.modules.woms.entity.Worker;
import cn.gzjp.modules.woms.service.WorkerService;

/**
 * 工作人员Controller
 * @author liyp
 * @version 2018-07-07
 */
@Controller
@RequestMapping(value = "${adminPath}/woms/worker")
public class WorkerController extends BaseController {

	@Autowired
	private WorkerService workerService;
	@Autowired
	private QyWxService qyWxService;



	
	
	/**
	 * 工作人员列表页面
	 */
	@RequiresPermissions("woms:worker:list")
	@RequestMapping(value = {"list", ""})
	public String list(Worker worker, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Worker> page = workerService.findPage(new Page<Worker>(request, response), worker); 
		model.addAttribute("page", page);
		return "modules/woms/workerList";
	}

	/**
	 * 查看，增加，编辑工作人员表单页面
	 */
	@RequiresPermissions(value={"woms:worker:view","woms:worker:add","woms:worker:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Worker worker, Model model) {
		model.addAttribute("worker", worker);
		return "modules/woms/workerForm";
	}




	/**
	 * 保存工作人员
	 */
	@RequiresPermissions(value={"woms:worker:add","woms:worker:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(Worker worker, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, worker)){
			return form(worker, model);
		}


		if(!worker.getIsNewRecord()){//编辑表单保存
			Worker t = workerService.get(worker.getId());//从数据库取出记录的值
			if(t!=null&&StringUtils.isNotBlank(t.getMobile())&&!t.getMobile().equals(worker.getMobile())){//修改了手机号，旧的手机号不等于新的手机号
				Worker have = workerService.findUniqueByMobile(worker.getMobile());
				if(have!=null){
					have = workerService.get(have.getId());
					if(have.getDelFlag().equals("0")){//存在且不是删除
						addMessage(redirectAttributes, "该手机号工作人员已存在，修改失败");
						return redirect("/woms/worker/?repage");
					}
					have.setDelFlag("0");//醒来
					have.setUpdateDate(new Date());
					workerService.save(have);//保存
				}
			}else{
				MyBeanUtils.copyBeanNotNull2Bean(worker, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
				t.setUpdateDate(new Date());
				workerService.save(t);//保存
			}
		}else{//新增表单保存
			Worker have = workerService.findUniqueByMobile(worker.getMobile());
			if(have!=null){
				worker = workerService.get(have.getId());
				if(worker.getDelFlag().equals("0")){//存在且不是删除
					addMessage(redirectAttributes, "该手机号工作人员已存在，新增失败");
					return redirect("/woms/worker/?repage");
				}else{//已删除
					worker.setDelFlag("0");//醒来
					workerService.save(worker);//保存
				}
			}else{//真正的新用户
				workerService.save(worker,worker.getMobile());//保存
			}

		}
		if(!corpDebug){//测试模式
			WxCpUser wxUser = new WxCpUser();
			wxUser.setUserId(worker.getId());
			wxUser.setMobile(worker.getMobile());
			wxUser.setName(worker.getName());
			Integer[] departIds = new Integer[1];
			departIds[0] = Integer.parseInt(worker.getRoles());
			wxUser.setDepartIds(departIds);
			WxCpService wxCpService = this.qyWxService.getWxCpService(corpId, Constants.AgentId.worker);//通讯录
			try {
				WxCpUser existUser = wxCpService.userGet(wxUser.getUserId());
				if(existUser==null){
					wxCpService.userCreate(wxUser);//同步到企业号
				}else{
					wxCpService.userUpdate(wxUser);//更新到企业号
				}
			} catch (WxErrorException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				wxCpService.userCreate(wxUser);//同步到企业号
			}
			WxCpUser existUser = wxCpService.userGet(wxUser.getUserId());
			if(existUser!=null){
				worker.setHeadImg(existUser.getAvatar());//更新头像
				workerService.save(worker);
			}

		}
		addMessage(redirectAttributes, "保存工作人员成功");
		return redirect("/woms/worker/");
	}
	
	/**
	 * 删除工作人员
	 */
	@RequiresPermissions("woms:worker:del")
	@RequestMapping(value = "delete")
	public String delete(Worker worker, RedirectAttributes redirectAttributes) {
		if(!worker.getId().equals(worker.getMobile())){
			addMessage(redirectAttributes, "该人员为微信企业管理人员，无法删除");
			return redirect("/woms/worker/?repage");
		}
		WxCpService wxCpService = this.qyWxService.getWxCpService(corpId, Constants.AgentId.worker);//通讯录
		try {
			wxCpService.userDelete(worker.getId());
			workerService.delete(worker);
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
		addMessage(redirectAttributes, "删除工作人员成功");
		return redirect("/woms/worker/?repage");
	}
	
	/**
	 * 批量删除工作人员
	 */
	@RequiresPermissions("woms:worker:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workerService.delete(workerService.get(id));
		}
		addMessage(redirectAttributes, "删除工作人员成功");
		return redirect("/woms/worker/");
	}

	/**
	 * 查看，增加，编辑工作人员表单页面
	 */
	@RequiresPermissions(value={"woms:worker:view","woms:worker:add","woms:worker:edit"},logical=Logical.OR)
	@RequestMapping(value = "account")
	public String account(Worker worker, Model model) {
		model.addAttribute("worker", worker);
		return "modules/woms/workerAccount";
	}


	/**
	 * 查看，增加，编辑工作人员表单页面
	 */
	@RequiresPermissions(value={"woms:worker:view","woms:worker:add","woms:worker:edit"},logical=Logical.OR)
	@RequestMapping(value = "saveAccount")
	public String saveAccount(Worker worker, RedirectAttributes redirectAttributes) {
		workerService.save(worker);
		addMessage(redirectAttributes, "设置账号成功");
		return redirect("/woms/worker/");
	}

	@ModelAttribute
	public Worker get(@RequestParam(required=false) String id) {
		Worker entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workerService.get(id);
		}
		if (entity == null){
			entity = new Worker();
		}
		return entity;
	}
	

}